package com.mammoth.Bodybuilding.util;

import java.io.File;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * 
 * @title : EmailUtil
 * @description : 电子邮件 工具类
 * @company : com.mammoth.Bodybuilding.util
 * @project Mammoth
 * @author xingzhaojun
 * @date 2018年4月22日 下午3:47:39
 */
@Component
public class EmailUtil {
	/** 自动注入的Bean **/
	@Autowired
	private JavaMailSender mailSender;
	/** 读取配置文件中的参数 **/
	@Value("${spring.mail.username}")
	private String Sender;

	/**
	 * 发送普通邮件
	 * 
	 * @param email
	 *            收件人
	 * @param subject
	 *            主题
	 * @param text
	 *            内容
	 * @throws Exception
	 */
	public void sendSimpleMail(String email, String subject, String text) throws Exception {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(Sender);
		message.setTo(email);
		message.setSubject(subject);
		message.setText(text);
		mailSender.send(message);
	}

	/**
	 * 电子邮件发送html
	 * 
	 * @param email
	 *            收件人
	 * @param subject
	 *            主题
	 * @param html
	 *            html代码
	 */
	public void sendHtmlMail(String email, String subject, String html) {
		MimeMessage message = null;
		try {
			message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(Sender);
			helper.setTo(email);
			helper.setSubject(subject);
			helper.setText(html, true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		mailSender.send(message);
	}

	/**
	 * 发送带有附件的电子邮件
	 * 
	 * @param email
	 *            收件人
	 * @param subject
	 *            主题
	 * @param text
	 *            内容
	 * @param sendfile
	 *            发送的文件
	 */
	public void sendAttachmentsMail(String email, String subject, String text, File sendfile) {
		MimeMessage message = null;
		try {
			message = mailSender.createMimeMessage();
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setFrom(Sender);
			helper.setTo(email);
			helper.setSubject(subject);
			helper.setText(text);
			/** 注意项目路径问题，自动补用项目路径 **/
			FileSystemResource file = new FileSystemResource(sendfile);
			/** 加入邮件 **/
			helper.addAttachment("file", file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		mailSender.send(message);
	}

}
